import axios from './axios'

/**
 * 返回数据类型
 * */
export interface HttpResponse {
    /** @description 状态码 */
    code: number
    /** @description 成功标志 */
    success: boolean
    /** @description 提示信息 */
    message?: string
    /** @description 返回数据 */
    data: any
}

/**
 * 拼接 get 请求参数
 * */
const splitParams = (params: Record<string, any>) => {
    let url = ''
    Object.keys(params).forEach((item, index) => {
        url += `${index ? '&' : '?'}${item}=${params[item]}`
    })
    return url
}

// 请求方法
type Methods = 'post' | 'get' | 'put' | 'delete'

// 请求参数类型
type HttpParams = (method: Methods, url: string, data?: Record<string, any>) => Promise<HttpResponse>

/**
 * 请求封装
 * */
const http: HttpParams = (method, url, data) => new Promise((resolve, reject) => {
    // 请求信息
    const config: Record<string, any> = {
        method,
        url
    }
    if (method === 'get' && data) config.url = `${url}${splitParams(data)}`
    if ((method === 'post') && data) config.data = data
    if ((method === 'delete') && data) config.params = data
    // 请求
    axios(config).then(res => {
        resolve(res)
    }).catch(err => {
        reject(err)
    })
})

export default http
